import axios from "axios";
import { config } from "./config";
import helper from "@/utils/helper";
import { Modal } from "ant-design-vue";
import { useUserStore } from "@/store/modules/user";
const { baseURL, contentType, requestTimeout, successCode, tokenPrefix } = config;

const instance = axios.create({
    baseURL,
    timeout: requestTimeout,
    headers: {
        "Content-Type": contentType,
        Authorization: "",
    },
});

// request interceptor
instance.interceptors.request.use(
    (config) => {
        // do something before request is sent
        const store = useUserStore();
        let token = store.token;
        if (token) {
            config.headers.Authorization = tokenPrefix + token;
        }
        return config;
    },
    (error) => {
        // do something with request error
        return Promise.reject(error);
    }
);

// response interceptor
instance.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */
    (response) => {
        const res = response.data;
        // 请求出错处理
        if (res.code === -1) {
            if (res.msg != null) helper.error(res.msg);
            return res;
        }
        if (successCode.indexOf(res.status) !== -1) {
            return Promise.reject(res);
        }
        return res;
    },
    (error) => {
        if (error.isAxiosError) {
            if (error.response != undefined && error.response.status == 401) {
                Modal.confirm({
                    title: "警告",
                    content: "账号异常，您可以取消停留在该页上，或重新登录",
                    okText: "重新登录",
                    cancelText: "取消",
                    onOk: () => {
                        localStorage.clear();
                        window.location.reload();
                    },
                });
            } else {
                helper.error("服务异常!" + error.message);
            }
        }
        return Promise.reject(error);
    }
);

export default instance;
